/*
** 标准套餐4 
*  接口文档：https://device.harmonyos.com/cn/docs/documentation/DevicePartner-References/obtain-registered-devices-0000001090265827
*/
import storeManage from "../store/index";
import Utils from "../utils/Utils";
export default class BleManage {
    constructor() {
        console.log("BleManage => constructor");
        // 是否ios设备
        this.isIOS = false;
        // android设备id 用于区分设备的 id，是用户选中的蓝牙设备的MAC地址或序列号SN
        this.deviceId = "";
        // 云端分配的设备唯一标示（设备id）
        this.hilinkDevId = "";
        // 定时器
        this.timer = null;
        // 0：初始未连接状态 1：连接中 2：已连接 3: 连接超时
        this.status = 0;
        // 蓝牙是否打开
        this.isBleAdapterOpened = false;
        // 是否正在发送指令
        this.isSenddingCommand = false;
    };

    /**
    * 初始化
    */
    init() {
        if (this.isExsitHilink()) {
            console.log("BleManage => init");
            this.getSystemInfo();
        }
    };

    /**
    * 是否存在hilink
    */
    isExsitHilink() {
        if (!window.hilink) {
            console.log("BleManage => no hilink ");
            return false;
        } else {
            return true;
        }
    };

    /**
    * 获取手机系统信息,判断手机操作系统是 Android 还是 iOS
    */
    getSystemInfo() {
        let self = this;
        if (self.isExsitHilink()) {
            console.log("BleManage => getSystemInfo");
            window.getSystemInfoSyncCallback = (res) => {
                let result = JSON.parse(res);
                console.log("BleManage getSystemInfo => ", result);
                storeManage.commit("ble/setSystemInfo", result);
                //判断是否Ios设备
                self.isIOS = result.platform === "iOS" ? true : false;
                storeManage.commit("setIsIos", self.isIOS);
                self.listeningBleChange();
                self.getBleState();

            };
            window.hilink.getSystemInfoSync("getSystemInfoSyncCallback");
        }
    };

    /**
    * 监听蓝牙变化,主动打开或关闭蓝牙会触发
    */
    listeningBleChange() {
        let self = this;
        if (self.isExsitHilink()) {
            console.log("BleManage => listeningBleChange");
            window.onBlueToothAdapterStateChangeCallback = (res) => {
                // 监听蓝牙状态回调函数
                let result = JSON.parse(res);
                console.log("BleManage => listeningBleChange => ", result);
                //蓝牙适配器是否可用
                let available = result.available;
                //是否正在搜索设备
                //let discovering = data.discovering;
                if (available) {
                    self.isBleAdapterOpened = true;
                    self.getRegisteredDevice();
                } else {
                    self.changeStatus(0);
                    self.clearTimer();
                    self.timer = null;
                    self.isBleAdapterOpened = false;
                }
            };
            window.hilink.onBluetoothAdapterStateChange("onBlueToothAdapterStateChangeCallback");
        }
    };

    /**
    * 获取当前蓝牙模块状态
    */
    getBleState() {
        let self = this;
        if (self.isExsitHilink()) {
            console.log("BleManage => getBleState");
            window.getBlueToothAdapterStateCallback = (res) => {
                let result = JSON.parse(res);
                console.log("BleManage => getBleState => ", result);
                //蓝牙适配器是否可用
                let available = result.available;
                //是否正在搜索设备
                //let discovering = data.discovering;
                //错误码：0, 90001
                //let errCode = data.errCode;
                if (available) {
                    self.getRegisteredDevice();
                } else {
                    self.openBlueTooth();
                }
            };
            window.hilink.getBluetoothAdapterState("getBlueToothAdapterStateCallback");
        }
    };

    /**
    * 获取宫格页面中选择的已注册的设备
    */
    getRegisteredDevice() {
        let self = this;
        if (self.isExsitHilink()) {
            console.log("BleManage => getRegisteredDevice");
            self.changeStatus(1);
            window.getCurrentRegisteredDeviceCallback = (res) => {
                let result = JSON.parse(res);
                console.log("BleManage => getRegisteredDevice => ", result);
                self.hilinkDevId = result.hilinkDevId;
                let deviceInfo = result.hilinkDeviceEntity;
                storeManage.commit("ble/setDeviceInfo", deviceInfo);
                if (!self.isIOS) {
                    // android
                    self.deviceId = result.deviceId;
                    self.connectForAndroid();
                }
            };
            window.hilink.getCurrentRegisteredDevice("getCurrentRegisteredDeviceCallback");
            self.createTimer();
        }
    };
    /**
    * 连接(android)
    */
    connectForAndroid() {
        let self = this;
        if (self.isExsitHilink()) {
            console.log("BleManage => connectForAndroid ");
            window.subscribeBleEventCallback = (res) => {
                //有数据主动上报时,返回的结果json格式有问题,要手动处理一下
                let result = Utils.jsonParse(res); //JSON.parse(res);
                console.log("BleManage => connectForAndroid => ", result);
                //let mac = data.mac;
                //type上报事件类型
                //CharacteristicChanged表示profile数据变化
                //ConnectionStateChange表示连接状态变化
                let callBackType = result.type;
                if (callBackType === 'ConnectionStateChange') {
                    self.dealConnectionStateChange(result);
                } else if (callBackType === 'CharacteristicChanged') {
                    self.dealCharacteristicChanged(result);
                }
            };
            // 订阅蓝牙事件
            window.hilink.subscribeBleEvent(self.hilinkDevId, self.deviceId, "subscribeBleEventCallback");
            window.connectBleCallback = (res) => {
                let result = JSON.parse(res);
                if (result.errcode === 0) {
                    console.log("BleManage => connectForAndroid success");
                    //跟固件对齐,连接成功后统一发这条指令,获取所有设备信息
                    self.sendCommand('getStateinfo', { all: 0 });
                } else {
                    console.log("BleManage => connectForAndroid fail");
                }
            };
            window.hilink.connectBle(self.hilinkDevId, self.deviceId, "connectBleCallback");
        }
    };
    /**
     * 处理设备连接状态
     */
    dealConnectionStateChange(result) {
        //变化后的BLE连接状态，0表示断开，1表示连接中，2表示已连接。
        let newStatus = result.newStatus;
        self.changeStatus(newStatus);
        if (newStatus === 2) {
            console.log("BleManage => dealConnectionStateChange =>  connect success ");
            // 连接成功
            self.clearTimer();
        } else if (newStatus === 1) {
            console.log("BleManage => dealConnectionStateChange =>  connectting ");
        } else if (newStatus === 0) {
            console.log("BleManage => dealConnectionStateChange =>  connect fail ");
            // 重新连接。
            // self.reConnectForAndroid();
        }
    };
    /**
     * 处理设备上报数据
     */
    dealCharacteristicChanged(result) {
        //profile完整内容。
        let content = result.content;
        //characterName及对应characterValue值。
        let data = result.data;
        //发生变化或查询的sid。
        let sid = result.sid;
        console.log("BleManage => dealCharacteristicChanged =>  content => ", content);
        console.log("BleManage => dealCharacteristicChanged =>  data => ", data);
        console.log("BleManage => dealCharacteristicChanged =>  sid => ", sid);
        let contentData = content.data;
        //如果获取所有信息失败，则状态置为重新连接。也可以去调用self.sendCommand('getStateinfo', { all: 0 }) 去重新获取
        if (contentData && contentData.all != 0) {
            console.log("BleManage => dealCharacteristicChanged =>  get all data fail",);
            self.changeStatus(0);
        }
    };

    /**
    * 重新连接(android)
    */
    reConnectForAndroid() {
        console.log("BleManage => reConnectForAndroid ");
        if (this.deviceId && this.hilinkDevId) {
            this.unSubscribeBleEvent();
            this.connectForAndroid();
            this.createTimer()
            return false;
        }
        this.init();
    };

    /**
    * 打开手机蓝牙
    */
    openBlueTooth() {
        if (this.isExsitHilink()) {
            console.log("BleManage => openBlueTooth ");
            window.hilink.openBluetoothAdapter();
        }
    };

    /**
    * 取消蓝牙订阅
    */
    unSubscribeBleEvent() {
        if (this.isExsitHilink()) {
            console.log("BleManage => unSubscribeBleEvent ");
            window.unSubscribeBleEventCallback = (res) => {
                let data = JSON.parse(res);
                console.log("BleManage => unSubscribeBleEvent => ", data);
            }
            window.hilink.unSubscribeBleEvent(this.hilinkDevId, this.deviceId, "unSubscribeBleEventCallback");
        }
    };

    /**
    * 断开蓝牙连接
    */
    disconnectBle() {
        if (this.isExsitHilink()) {
            console.log("BleManage => disconnectBle ");
            window.disconnectBleCallback = (res) => {
                let data = JSON.parse(res);
                console.log("BleManage => disconnectBle => ", data);
            }
            window.hilink.disconnectBle(this.hilinkDevId, this.deviceId, "disconnectBleCallback");
        }
    };

    /**
    * 清除设备BLE用户注册信息
    */
    clearBleRegInfo() {
        if (this.isExsitHilink()) {
            console.log("BleManage => clearBleRegInfo ");
            window.clearBleRegInfoCallback = (res) => {
                let data = JSON.parse(res);
                console.log("BleManage => clearBleRegInfo => ", data);
            }
            window.hilink.clearBleRegInfo(this.hilinkDevId, this.deviceId, "clearBleRegInfoCallback");
        }
    };

    /**
    * 删除云端BLE设备
    */
    deleteDevice() {
        if (this.isExsitHilink()) {
            console.log("BleManage => deleteDevice ");
            window.deleteDeviceCallback = (res) => {
                let data = JSON.parse(res);
                console.log("BleManage => deleteDevice => ", data);
            }
            window.hilink.deleteDevice(this.hilinkDevId, "deleteDeviceCallback");
        }
    };

    /**
    * 发送蓝牙设备命令
    * @param {string} serviceId - 设备服务ID，示例：lightSwitch。
    * @param {string} data - 下发的控制命令数据，如{"on", 1}。如果查询sid对应的profile数据，则该字段填写“”。
    * @param {Function} callback - 回调
    */
    sendCommand(serviceId, data, callback) {
        if (this.isSenddingCommand) {
            console.log("BleManage => sendCommand => sendding");
            return false;
        }
        if (this.isExsitHilink()) {
            this.isSenddingCommand = true;
            console.log("BleManage => sendCommand ", data);
            window.sendCommandCallback = (res) => {
                this.isSenddingCommand = false;
                if (callback) callback(res);
            };
            window.hilink.sendCommand(this.hilinkDevId, this.deviceId, serviceId, JSON.stringify(data), "sendCommandCallback");
        }
    };
    /**
    * 状态变化事件
    */
    changeStatus(status) {
        console.log("BleManage => changeStatus ", status);
        this.status = status;
        storeManage.commit('ble/setBleSatuts', status);
    };

    /**
    * 设置标题栏是否可见
    * 
    * @param {boolean} visible - 是否显示
    */
    setTitleVisible(visible) {
        if (this.isExsitHilink()) {
            console.log("BleManage => setTitleVisible ", visible);
            window.hilink.setTitleVisible(visible);
        }
    };

    /**
    * ota升级检测
    * 
    * @param {Function} callback - 回调
    */
    checkDeviceHota(callback) {
        let self = this;
        if (self.isExsitHilink()) {
            console.log("BleManage => checkDeviceHota ");
            window.checkDeviceHotaCallback = (res) => {
                let result = JSON.parse(res);
                console.log("BleManage => checkDeviceHota ", result);
                //固件版本检测结果
                let checkVersionResult = result.checkVersionResult;
                // let newVersion = result.newVersion;
                // let description = result.description;
                if (checkVersionResult) {
                    self.jumpTo(callback);
                }
            }
            window.hilink.checkDeviceHota(this.deviceId, this.hilinkDevId, 'checkDeviceHotaCallback');
        }
    };
    /**
    * 页面升级跳转
    */
    jumpTo(callback) {
        window.jumpToCallback = (jumpres) => {
            console.log("BleManage => checkDeviceHota ", jumpres);
            if (callback) callback();
        }
        window.hilink.jumpTo('com.huawei.smarthome.deviceBleUpgradeActivity', 'jumpToCallback');
    };
    /**
    * 设置定时器
    */
    createTimer() {
        console.log("BleManage => createTimer ");
        let self = this;
        if (self.timer !== null) {
            return false;
        }
        self.timer = setTimeout(function () {
            self.changeStatus(3);
            self.clearTimer();
            self.timer = null;
        }, 30 * 1000);
    };
    /**
    * 清除定时器
    */
    clearTimer() {
        console.log("BleManage => clearTimer ");
        clearTimeout(this.timer);
    };

}
